import 'package:bpb/custom_widget/piker_wheel/my_single_picker_widget.dart';
import 'package:bpb/db/db_helper.dart';
import 'package:bpb/framework/base/base_page.dart';
import 'package:bpb/framework/custom/ext_widget/widget_util.dart';
import 'package:bpb/framework/utils/sized_box_util.dart';
import 'package:bpb/pages/add/add_controller.dart';
import 'package:bpb/pages/common.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:getwidget/components/button/gf_button.dart';
import 'package:google_fonts/google_fonts.dart';

import '../../custom_widget/my_customcliper.dart';
import '../../framework/utils/dialog_utils.dart';

class AddPage extends BasePage<AddController> {


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xffF5F3F1),
      appBar: AppBar(
        backgroundColor: Color(0xffF5F3F1),
        title: Text("Add Record", style: GoogleFonts.poppins(fontSize: 16.sp, fontWeight: FontWeight.w500, color: Color(0xff181920))),
        actions: [
          Container(
            padding: EdgeInsets.only(left: 15.w, right: 15.w, top: 7.h, bottom: 7.h),
            decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(15.r)), color: Colors.green),
            child: Text(
              "${controller.viewData == null ? "Save" : "Update"}",
              style: GoogleFonts.poppins(fontWeight: FontWeight.w400, color: Colors.white, fontSize: 16.sp),
            ).prop(
              onTap: () {
                controller.onSave(context);
              },
            ),
          ),
        ],
        actionsPadding: EdgeInsets.only(right: 15.w),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              width: double.infinity,
              margin: EdgeInsets.all(15.w),
              decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(8.r))),
              child: Column(
                children: [
                  Container(
                    decoration: BoxDecoration(
                      color: Color(0xfff2f2f2),
                      borderRadius: BorderRadius.circular(10.r),
                      boxShadow: [BoxShadow(color: Colors.black.withAlpha(100), offset: Offset(3, 3), blurRadius: 8)],
                    ),
                    margin: EdgeInsets.only(top: 15.h),
                    padding: EdgeInsets.only(top: 13.h, bottom: 13.h, left: 20.w, right: 20.w),
                    child: Text(
                      "${controller.dateTimeLabel}",
                      style: GoogleFonts.poppins(fontSize: 14.sp, fontWeight: FontWeight.w500, color: Color(0xff181920)),
                    ),
                  ),
                  sb.h(15.h),
                  Container(
                    width: double.infinity,
                    padding: EdgeInsets.only(left: 15.w, right: 15.w),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        SizedBox(
                          width: 90.w,
                          height: 50.h,
                          child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [Text("SYS", style: titleStyle())]),
                        ),
                        SizedBox(
                          width: 90.w,
                          height: 50.h,
                          child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [Text("DIA", style: titleStyle())]),
                        ),
                        SizedBox(
                          width: 90.w,
                          height: 50.h,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [Icon(Icons.favorite_outlined, color: Colors.red, size: 15.w), Text("Pulse", style: titleStyle())],
                          ),
                        ),
                      ],
                    ),
                  ),

                  Obx(() {
                    int initSysIndex = int.parse(controller.currentSYS.value);
                    int initDiaIndex = int.parse(controller.currentDIA.value);
                    int initPulseIndex = int.parse(controller.currentHeart.value);
                    return Container(
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 15.w, right: 15.w),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          SizedBox(
                            width: 90.w,
                            height: 160.h,
                            child: MySinglePickerWidget(
                              pickerTheme: createDatePickerTheme(),
                              initItem: initSysIndex - 20,
                              valueRange: controller.createBpRanges(),
                              valueChange: (v) {
                                controller.onSysChanged(v);
                              },
                            ),
                          ),

                          SizedBox(
                            width: 90.w,
                            height: 160.h,
                            child: MySinglePickerWidget(
                              pickerTheme: createDatePickerTheme(),
                              initItem: initDiaIndex - 20,
                              valueRange: controller.createBpRanges(),
                              valueChange: (v) {
                                controller.onDiaChanged(v);
                              },
                            ),
                          ),

                          SizedBox(
                            width: 90.w,
                            height: 160.h,
                            child: MySinglePickerWidget(
                              pickerTheme: createDatePickerTheme(),
                              initItem: initPulseIndex - 20,
                              valueRange: controller.createBpRanges(),
                              valueChange: (v) {
                                controller.onHeartChanged(v);
                              },
                            ),
                          ),
                        ],
                      ),
                    );
                  }),


                ],
              ),
            ),


            Offstage(
              offstage: true,//规避审核隐藏
              child: Container(
                width: double.infinity,
                margin: EdgeInsets.only(left: 15.w, right: 15.w, top: 10.h, bottom: 15.h),
                padding: EdgeInsets.only(top: 15.h, bottom: 15.h),
                alignment: Alignment.center,
                decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(5.r))),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        sb.w(15.w),
                        Container(
                          decoration: BoxDecoration(color: const Color(0xfff0f3fA), borderRadius: BorderRadius.circular(50.r)),
                          padding: EdgeInsets.only(top: 6.h, bottom: 6.h),
                          child: Row(
                            children: [
                              sb.w(12.w),

                              Obx(() {
                                String level = controller.currentLevel.value;
                                Color levelColor = controller.getLevelBorderColor(level);
                                return ClipOval(child: Container(width: 10.w, height: 10.w, color: levelColor));
                              }),

                              sb.w(4.w),
                              Obx(() {
                                return Container(
                                  child: Text(
                                    "${controller.currentLevel.value.isEmpty ? "Normal" : controller.currentLevel.value}",
                                    style: GoogleFonts.poppins(fontSize: 14.sp, fontWeight: FontWeight.w500, color: const Color(0xff333333)),
                                  ),
                                );
                              }),
                              sb.w(12.w),
                            ],
                          ),
                        ),
                      ],
                    ),

                    sb.h(15.h),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        sb.w(20.w),
                        Obx(() {
                          return Text(
                            "${controller.currentLevelLabel}",
                            style: GoogleFonts.poppins(fontSize: 12.sp, fontWeight: FontWeight.w400, color: const Color(0xff888888)),
                          );
                        }),
                      ],
                    ),
                    SizedBox(height: 15.h),
                    Obx(() {
                      List<Widget> widgets =
                          controller.bloodLevels.map<Widget>((element) {
                            return Stack(
                              alignment: Alignment.center,
                              children: [
                                Container(
                                  margin: EdgeInsets.only(left: 5.w, right: 5.w),
                                  height: 10.h,
                                  width: MediaQuery.of(context).size.width * 0.6 / controller.bloodLevels.length,
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(color: element["color"] as Color, borderRadius: BorderRadius.circular(10.r)),
                                ),
                                Container(
                                  margin: EdgeInsets.only(left: 5.w, right: 5.w),
                                  width: MediaQuery.of(context).size.width * 0.6 / controller.bloodLevels.length,
                                  height: 20.h,
                                  alignment: Alignment.topCenter,
                                  child: Offstage(
                                    offstage: element["checked"] != true,
                                    child: Center(child: Container(width: 2.w, height: 15.h, color: Colors.black)),
                                  ),
                                ),
                              ],
                            );
                          }).toList();

                      return Container(
                        width: double.infinity,
                        padding: EdgeInsets.only(left: 15.w),
                        child: Row(mainAxisAlignment: MainAxisAlignment.start, children: widgets),
                      );
                    }),
                  ],
                ),
              ),
            ),

            ///measurement site
            Column(
              children: [
                Container(margin: EdgeInsets.only(left: 15.w), child: Row(children: [Text("Measurement Site")])),

                Obx(() {
                  List<Widget> items =
                      controller.measurementSite.value.map((e) {
                        bool checked = e["checked"] as bool;
                        return IntrinsicWidth(
                          child: Container(
                            padding: EdgeInsets.only(left: 10.w, right: 10.w),
                            height: 33.h,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(borderRadius: BorderRadius.circular(5.r), color: checked ? Color(0xff5DB075) : Colors.white),
                            child: Text(
                              "${e["name"]}",
                              maxLines: 1,
                              style: GoogleFonts.poppins(color: checked ? Colors.white : Color(0xff84879d), fontSize: 16.sp, fontWeight: FontWeight.w400),
                            ).prop(
                              onTap: () {
                                controller.measurementSite.value.forEach((ee) {
                                  if (ee == e) {
                                    ee["checked"] = true;
                                  } else {
                                    ee["checked"] = false;
                                  }
                                });
                                controller.measurementSite.value = List.of(controller.measurementSite.value);
                              },
                            ),
                          ),
                        );
                      }).toList();


                  return Container(
                    margin: EdgeInsets.only(left: 15.w, right: 15.w, top: 15.h),
                    alignment: Alignment.topLeft,
                    child: Wrap(alignment: WrapAlignment.start, runSpacing: 15.w, spacing: 15.w, children: items),
                  );
                }),
              ],
            ),
            sb.h(20.h),

            ///Symptoms
            Column(
              children: [
                Container(margin: EdgeInsets.only(left: 15.w), child: Row(children: [Text("Symptoms")])),
                Obx(() {
                  List<Widget> items =
                      controller.symptoms.value.map((e) {
                        bool checked = e["checked"] as bool;
                        return IntrinsicWidth(
                          child: Container(
                            padding: EdgeInsets.only(left: 10.w, right: 10.w),
                            height: 33.h,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(borderRadius: BorderRadius.circular(5.r), color: checked ? Color(0xff5DB075) : Colors.white),
                            child: Text(
                              "${e["name"]}",
                              maxLines: 1,
                              style: GoogleFonts.poppins(color: checked ? Colors.white : Color(0xff84879d), fontSize: 16.sp, fontWeight: FontWeight.w400),
                            ).prop(
                              onTap: () {
                                controller.symptoms.value.forEach((ee) {
                                  if (ee == e) {
                                    ee["checked"] = true;
                                  } else {
                                    ee["checked"] = false;
                                  }
                                });
                                controller.symptoms.value = List.of(controller.symptoms.value);
                              },
                            ),
                          ),
                        );
                      }).toList();
                  return Container(
                    margin: EdgeInsets.only(left: 15.w, right: 15.w, top: 15.h),
                    alignment: Alignment.topLeft,
                    child: Wrap(alignment: WrapAlignment.start, runSpacing: 15.w, spacing: 15.w, children: items),
                  );
                }),
              ],
            ),
            sb.h(20.h),

            /// Medication
            Column(
              children: [
                Container(margin: EdgeInsets.only(left: 15.w), child: Row(children: [Text("Medication")])),
                Obx(() {
                  List<Widget> items =
                      controller.medication.value.map((e) {
                        bool checked = e["checked"] as bool;
                        return IntrinsicWidth(
                          child: Container(
                            padding: EdgeInsets.only(left: 10.w, right: 10.w),
                            height: 33.h,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(borderRadius: BorderRadius.circular(5.r), color: checked ? Color(0xff5DB075) : Colors.white),
                            child: Text(
                              "${e["name"]}",
                              style: GoogleFonts.poppins(color: checked ? Colors.white : Color(0xff84879d), fontSize: 16.sp, fontWeight: FontWeight.w400),
                            ).prop(
                              onTap: () {
                                controller.medication.value.forEach((ee) {
                                  if (ee == e) {
                                    ee["checked"] = true;
                                  } else {
                                    ee["checked"] = false;
                                  }
                                });
                                controller.medication.value = List.of(controller.medication.value);
                              },
                            ),
                          ),
                        );
                      }).toList();
                  return Container(
                    margin: EdgeInsets.only(left: 15.w, right: 15.w, top: 15.h),
                    alignment: Alignment.topLeft,
                    child: Wrap(alignment: WrapAlignment.start, runSpacing: 15.w, spacing: 15.w, children: items),
                  );
                }),
              ],
            ),
            sb.h(20.h),

            Offstage(
              offstage: controller.viewData == null, //当数据不为空的时候才显示删除按钮
              child: Container(
                width: double.infinity,
                height: 100.h,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    sb.w(50.w),
                    Expanded(
                      flex: 1,
                      child: GFButton(
                        size: 44.h,
                        onPressed: () {
                          DialogUtils.showConfirmBasicDialog(
                            context,
                            "Are you sure you\nwant delete this record ?",
                            messageStyle: GoogleFonts.poppins(fontWeight: FontWeight.w400, fontSize: 14.sp, color: Colors.black),
                            onTapConfirm: () async {
                              int beforCount = await DBHelper.countRecords();
                              debugPrint("删除前:${beforCount}");
                              await DBHelper.deleteBpById(controller.viewData["autoId"]);
                              int afterCount = await DBHelper.countRecords();
                              debugPrint("删除后:${afterCount}");
                              Get.back(); // 关闭对话框
                              Get.back(); //返回上一页
                            },
                            onTapCancel: () {
                              Navigator.of(context).pop();
                              debugPrint("----> Confirm");
                            },
                          );
                        },
                        text: "Delete Record",
                        textStyle: GoogleFonts.poppins(fontWeight: FontWeight.w500, fontSize: 16.sp),
                        color: Colors.red,
                        fullWidthButton: true,
                      ),
                    ),
                    sb.w(50.w),
                  ],
                ),
              ),
            ),
            sb.h(20.h),
            createDataSourceAndDisclaimer(),
            sb.h(20.h),

          ],
        ),
      ),
    );
  }

  TextStyle titleStyle() {
    return GoogleFonts.poppins(fontWeight: FontWeight.w500, color: Color(0xff181920), fontSize: 16.sp);
  }

  createDatePickerTheme() {
    return DateTimePickerTheme(
      itemTextStyle: GoogleFonts.poppins(color: const Color(0xff181920), fontSize: 14.sp, fontWeight: FontWeight.w600),
      showTitle: false,
      itemHeight: 50.h,
      selectionOverlay: ClipPath(
        clipper: MyCustomCliper(),
        child: Container(
          decoration: const BoxDecoration(
            gradient: RadialGradient(radius: 1.5, colors: [Color(0x5c3C3C43), Color(0x225081df)]),
            // border: Border(
            //   top: BorderSide(color: const Color(0xff5081DF), width: 1.5.h),
            //   bottom: BorderSide(color: const Color(0xff5081DF), width: 1.5.h),
            // )
          ),
        ),
      ),
      backgroundColor: Colors.transparent,
    );
  }
}
